#include <pc.h>
#include <stdio.h>
#include "kbc.h"

int DEBUG_KBC = 0;

int  read_kbc(void){
	if (DEBUG_KBC == 1) printf("read : ");
	int time = 0;
	while (time < KBC_TIMEOUT) {
		int status = inportb(STAT_REG);
		if ((status & OBF) != 0) {
			if ((status & (TO_ERR | PAR_ERR)) != 0) {
				if (DEBUG_KBC == 1) printf("error\n");
				return -1;
			}
			int value = inportb(DATA_REG);
			if (DEBUG_KBC == 1) printf("data=%x\n", value);
			return value;
		}
		time++;
		delay(1);
	}
	if (DEBUG_KBC == 1) printf("timeout\n");
	return -1;
}


int  write_kbc(unsigned adr, unsigned data){
	if (DEBUG_KBC == 1) printf("write : ");
	int time = 0;
	while (time < KBC_TIMEOUT) {
		int status = inportb(STAT_REG);
		if ((status & IBF) == 0) {
			if (DEBUG_KBC == 1) printf("addr=%x data=%x\n", adr, data);
			outportb(adr, data);
			return 0;
		}
		time++;
		delay(1);
	}
	if (DEBUG_KBC == 1) printf("timeout\n");
	return -1;
}

